import React, { FunctionComponent } from "react";
import { useLocalStore, useObserver } from "mobx-react-lite";
import { ErrorCode, getErrorMessage } from "../../core/errorcode";
import openapi from "@anyshare/openapi";
import Button from "antd/lib/button";
import Input from "antd/lib/input";
import { useVerification } from "./verification-context";
import { VerificationType, IForgetPasswordState, ISendVerificationProps, ISendVerificationState } from "./type";
import { BackOutlined, PhoneColored, EmailColored } from "@anyshare/icons";

export const SendVerification: FunctionComponent<ISendVerificationProps> = ({ t, redirect }) => {
    const verification = useVerification() as IForgetPasswordState;
    const store = useLocalStore<ISendVerificationState>(() => {
        return {
            errorStatus: ErrorCode.Normal,
            get getInputName() {
                switch (true) {
                    case verification.sendVcodeType.sendVcodeBySMS && verification.sendVcodeType.sendVcodeByEmail:
                        return (
                            <React.Fragment>
                                <PhoneColored className="icon icon-opacity" style={{ paddingRight: "2px" }} />
                                <span className="icon-opacity">/</span>
                                <EmailColored className="icon icon-opacity" style={{ paddingLeft: "4px" }} />
                            </React.Fragment>
                        );

                    case verification.sendVcodeType.sendVcodeBySMS:
                        return <PhoneColored className="icon icon-opacity" />;
                    case verification.sendVcodeType.sendVcodeByEmail:
                        return <EmailColored className="icon icon-opacity" />;
                    default:
                        return "";
                }
            },
            get getPlaceholderContent(): string {
                switch (true) {
                    case verification.sendVcodeType.sendVcodeBySMS && verification.sendVcodeType.sendVcodeByEmail:
                        return t("bind-all");
                    case verification.sendVcodeType.sendVcodeBySMS:
                        return t("bind-phone");
                    case verification.sendVcodeType.sendVcodeByEmail:
                        return t("bind-email");
                    default:
                        return "";
                }
            },
            async sendVcode() {
                await verification.updatePasswordConfig();
                const verficationType = verification.getVerificationType;
                const { sendVcodeByEmail, sendVcodeBySMS } = verification.sendVcodeType;
                try {
                    if (verficationType === VerificationType.PHONE) {
                        // 短信验证
                        if (!sendVcodeBySMS) {
                            store.errorStatus = ErrorCode.SMSClose;
                        } else {
                            const { data } = await openapi.post(("/eacp/v1/auth1/sendvcode" as unknown) as any, {
                                telnumber: verification.verificationValue,
                                uuid: verification.verificationId,
                            });
                            verification.sendVcodeSuccess(
                                ((data as unknown) as any).uuid,
                                verficationType,
                                verification.verificationValue
                            );
                        }
                    } else if (verficationType === VerificationType.EMAIL) {
                        // 邮箱验证
                        if (!sendVcodeByEmail) {
                            store.errorStatus = ErrorCode.EmailClose;
                        } else {
                            const { data } = await openapi.post(("/eacp/v1/auth1/sendvcode" as unknown) as any, {
                                emailaddress: verification.verificationValue,
                                uuid: verification.verificationId,
                            });
                            verification.sendVcodeSuccess(
                                ((data as unknown) as any).uuid,
                                verficationType,
                                verification.verificationValue
                            );
                        }
                    } else {
                        // 验证类型为Verfication.NONE
                        switch (true) {
                            case sendVcodeBySMS && sendVcodeByEmail:
                                store.errorStatus = verification.verificationValue
                                    ? ErrorCode.InCorrect
                                    : ErrorCode.BlankNumber;
                                break;
                            case sendVcodeBySMS && !sendVcodeByEmail:
                                store.errorStatus = verification.verificationValue
                                    ? ErrorCode.CellphoneError
                                    : ErrorCode.BlankPhone;
                                break;
                            case !sendVcodeBySMS && sendVcodeByEmail:
                                store.errorStatus = verification.verificationValue
                                    ? ErrorCode.EmailError
                                    : ErrorCode.BlankEmail;
                                break;
                            case !sendVcodeBySMS && !sendVcodeByEmail:
                                store.errorStatus = ErrorCode.CloseForgetPasswordResetBySend;
                                break;
                            default:
                                break;
                        }
                    }
                } catch (e) {
                    if (e.response) {
                        const {
                            response: { data: err },
                        } = e;
                        switch (err.code) {
                            case ErrorCode.PasswordChangeNotSupported:
                                store.errorStatus =
                                    verficationType === VerificationType.PHONE
                                        ? ErrorCode.SMSUserNoLocal
                                        : ErrorCode.EmailUserNoLocal;
                                break;
                            case ErrorCode.PasswordRestricted:
                                store.errorStatus =
                                    verficationType === VerificationType.PHONE
                                        ? ErrorCode.SMSUserControlled
                                        : ErrorCode.EmailUserControlled;
                                break;
                            case ErrorCode.SendVcodeServerUnavailable:
                                store.errorStatus =
                                    verficationType === VerificationType.PHONE
                                        ? ErrorCode.SMSClose
                                        : ErrorCode.EmailClose;
                                break;
                            default:
                                store.errorStatus = err.code;
                        }
                    } else {
                        store.errorStatus = ErrorCode.NoNetwork;
                    }
                }
            },
        };
    });

    return useObserver(() => {
        return (
            <div className="content">
                <BackOutlined className="back back-pass" onClick={() => (location.href = redirect)} />
                <Input
                    className="input-item send-verification-item"
                    type="text"
                    prefix={store.getInputName}
                    placeholder={store.getPlaceholderContent}
                    value={verification.verificationValue}
                    onChange={(e) => {
                        verification.updateVerificationValue(e.target.value);
                        store.errorStatus = ErrorCode.Normal;
                    }}
                    onDrop={(e) => {
                        e.preventDefault();
                    }}
                />
                <Button
                    className="oem-button as-components-oem-background-color"
                    type="primary"
                    onClick={store.sendVcode}
                >
                    {t("send-captcha")}
                </Button>
                {store.errorStatus !== ErrorCode.Normal ? (
                    <div className="error-message-text">{getErrorMessage(store.errorStatus, t)}</div>
                ) : null}
            </div>
        );
    });
};
